package com.ye.personnel.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ye.personnel.api.department.GwyPullDepartmentListVo;
import com.ye.personnel.mapper.dao.GwyDepartmentMapper;
import com.ye.personnel.mapper.entity.GwyDepartment;
import com.ye.personnel.service.GwyCmsSystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: yeubo
 * @Date: 2024/1/3 16:41
 */
@Component
@Slf4j
public class PullGwyDepartmentTask {

    @Autowired
    GwyCmsSystemService gwyCmsSystemService;
    @Autowired
    GwyDepartmentMapper departmentMapper;

    //@Scheduled(cron = "0 0/1 * * * ?")
    public void pullDepartment(){
        List<GwyPullDepartmentListVo> departmentList = gwyCmsSystemService.pullDepartmentList();
        for (GwyPullDepartmentListVo departmentListVo : departmentList){
            String departmentNo = departmentListVo.getDepartmentNo();
            String parentDepartmentNo = departmentListVo.getParentDepartmentNo();
            String departmentName = departmentListVo.getDepartmentName();
            GwyDepartment department = departmentMapper.selectOne(new LambdaQueryWrapper<GwyDepartment>()
                    .eq(GwyDepartment::getDepartmentNo, departmentNo).last("limit 1"));
            if(department == null){
                GwyDepartment parentDepartment = departmentMapper.selectOne(new LambdaQueryWrapper<GwyDepartment>()
                        .eq(GwyDepartment::getDepartmentNo, parentDepartmentNo).last("limit 1"));
                GwyDepartment departmentInsert = new GwyDepartment();
                departmentInsert.setDepartmentName(departmentName);
                departmentInsert.setDepartmentNo(departmentNo);
                if(parentDepartment != null){
                    departmentInsert.setParentDepartmentId(parentDepartment.getDepartmentId());
                }
                departmentMapper.insert(departmentInsert);
            }else{
                department.setDepartmentName(departmentName);
                GwyDepartment parentDepartment = departmentMapper.selectOne(new LambdaQueryWrapper<GwyDepartment>()
                        .eq(GwyDepartment::getDepartmentNo, parentDepartmentNo).last("limit 1"));
                if(parentDepartment != null){
                    department.setParentDepartmentId(parentDepartment.getDepartmentId());
                }
                departmentMapper.updateById(department);
            }
        }
    }
}
